# -*- coding: utf-8 -*-
"""
 登获取token
 Created by Quant on 2018-03-08
"""
__author__ = 'Quant'

from flask_restful import Resource, reqparse, fields
from werkzeug.security import check_password_hash

from app.core import util, auth
from app.models import User
from app.core.redis import redis
from app.core.const import Const

parser = reqparse.RequestParser()
parser.add_argument('username', required=True, type=str)
parser.add_argument('password', required=True, type=str)

resource_full_fields = {
    'id': fields.Integer,
    'email': fields.String,
    'username': fields.String,
    'avatar': fields.String,
    'login_time': fields.Integer
}


# 用户登录、获取Token
class Login(Resource):
    def post(self):
        args = parser.parse_args()
        username = args['username']
        password = args['password']
        if (not username or not password):
            return util.error_result('用户名和密码不能为空')
        # 查询用户的数据
        user = User.query.filter_by(username=username).first()
        if (user is None):
            return util.error_result('找不到用户')
        # 验证密码的正确性
        flag = check_password_hash(user.password, password)
        # 如果密码正确
        if (not flag):
            return util.error_result('密码不正确,请重新输入正确的密码')
        # 生产token信息
        token = auth.create_auth_token(user.id).decode()
        # 放入到redis缓存中，便于记录账户的上下线，过期等操作
        redis.set(Const.AUTH_TOKEN.format(token), user.id, Const.AUTH_TOKEN_EXPIRES)

        return util.success_result(token, '登录成功')
